﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// A standard quicksearch-box, enabled with a 'watermark' and a listener which is fired when the enter key is pressed.
    /// It fires the event : SearchTextSubmitted
    /// After entering a searchphrase the control will redirect you to the given searchpage.
    /// </summary>
    /// <remarks>
    /// Uses the AjaxControlToolkit (for .Net 3.5) and "System.Web.Extensions v3.5"
    /// </remarks>
    public class SearchBox : Control, INamingContainer
    {
        protected TextBox searchText = new TextBox();
        protected Button searchButton = new Button();

        protected override void CreateChildControls()
        {
            searchText.ID = "txtSearchTextSearchBox";
            searchText.Attributes.Add("name", "searchtext");

            if (!string.IsNullOrEmpty(this.CssClassTextBox))
                searchText.CssClass = this.CssClassTextBox;

            this.Controls.Add(searchText);

            // Button
            searchButton.ID = "butSearchSearchBox";
            searchButton.Text = "Search";
            searchButton.CausesValidation = false; // no validation required
            if (!string.IsNullOrEmpty(this.CssClassButton))
                searchButton.CssClass = this.CssClassButton;
            searchButton.Text = string.IsNullOrEmpty(this.TextButton) ? "Search" : this.TextButton;
            this.Controls.Add(searchButton);
            searchButton.Click += new EventHandler(searchButton_Click); //event

            // Let a 'enter'command, press this button
            this.Page.TieButton(searchText, searchButton);
        }

        /// <summary>
        /// Get/Set the CssClass of the Textbox
        /// </summary>
        public string CssClassTextBox { get; set; }

        /// <summary>
        /// Get/Set the CssClass of the Button
        /// </summary>
        public string CssClassButton { get; set; }

        /// <summary>
        /// Get/Set the text of the button
        /// </summary>
        public string TextButton { get; set; }

        /// <summary>
        /// application relative Url (start with "~/") of the search(result)page. After doing a search-request, the user will be redirected to this page.
        /// The searchtext will be appended to the querystring. The default page is ~/Pages/Search.aspx
        /// </summary>
        /// <example>~/Pages/Search.aspx</example>
        public string SearchPageUrl { get; set; }

        /// <summary>
        /// The name of the querystring parameter which will be used when redirecting to the search-page. Default "search"
        /// </summary>
        public string SearchPageQueryStringParameter { get; set; }

        /// <summary>
        /// Get/Set if the user will be redirected to the searchpage when the entered query is emtpy. When not set search will NOT be
        /// performed without a searchquery.
        /// </summary>
        public bool? SearchWithEmptyQuery { get; set; }

        /// <summary>
        /// Event fired when button has been clicked. When the event is handled, only the event is fired. 
        /// When you don't listen to this event, the user will be redirected to the configured searchpage.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void searchButton_Click(object sender, EventArgs e)
        {
            string searchQuery = this.searchText.Text.Trim();

            //Check if the user has entered a query.
            if (string.IsNullOrEmpty(searchQuery) == false
                || (string.IsNullOrEmpty(searchQuery) && this.SearchWithEmptyQuery.HasValue && this.SearchWithEmptyQuery.Value == true))
            {
                //The event should only be fired when some control is waiting for this event.
                if (this.SearchTextSubmitted != null)
                {
                    SearchBoxEventArgs args = new SearchBoxEventArgs();
                    args.SearchText = searchQuery;
                    this.SearchTextSubmitted(this, args);
                }
                else
                {
                    //Redirect
                    string url = string.IsNullOrEmpty(this.SearchPageUrl) ? "~/Search.aspx" : this.SearchPageUrl;
                    string paramenterName = string.IsNullOrEmpty(this.SearchPageQueryStringParameter) ? "search" : this.SearchPageQueryStringParameter;
                    this.Page.Response.Redirect(string.Format("{0}?{1}={2}", url, paramenterName, searchQuery));
                }
            }

        }

        public event SearchBoxEventHandler SearchTextSubmitted;
    }

    public delegate void SearchBoxEventHandler(object sender, SearchBoxEventArgs e);

    public class SearchBoxEventArgs : System.EventArgs
    {
        public SearchBoxEventArgs()
            : base()
        { }

        /// <summary>
        /// Text entered.
        /// </summary>
        public string SearchText { get; set; }
    }
}
